<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 2016-03-16
 * Time: 19:12
 */

namespace common\services\common;

use common\entities\common\MyscrmDatabaseInstanceConfigEntity;
use common\entities\common\MyscrmXunjianDatabaseEntity;
use common\models\ConnectionModel;
use common\repositories\common\MyscrmXunjianDatabaseRepository;
use common\services\BaseService;
use Yii;
use yii\base\Exception;

class MyscrmXunjianDatabaseService extends BaseService
{
    public $repository;

    public function __construct(MyscrmXunjianDatabaseRepository $repository, $config = [])
    {
        $this->repository = $repository;

        return parent::__construct($config);
    }

    /**
     * @param $orgCode
     * @return ConnectionModel
     * @throws Exception
     */
    public function getDatabaseConnectionByOrgCode($orgCode)
    {
        $data = $this->repository->getDatabaseInstance($orgCode);

        if (empty($data)) {
            return null;
        }

        /* @var $databaseInstanceConfigService MyscrmDatabaseInstanceConfigService */
        $databaseInstanceConfigService = Yii::createObject(MyscrmDatabaseInstanceConfigService::className());
        $config = $databaseInstanceConfigService->getConfigById($data->database_instance_id);

        if (empty($config)) {
            return null;
        }

        return new ConnectionModel(
            [
                'host'     => $config->host,
                'port'     => $config->port,
                'dbname'   => $data->database_name,
                'username' => $config->username,
                'password' => $config->password,
                'instanceId' => $config->instance_id,
            ]
        );
    }

    public function assignDatabaseInstance($orgCode, $databaseInstanceId, $databaseName)
    {
        return $this->repository->assignDatabaseInstance($orgCode, $databaseInstanceId, $databaseName);
    }

    public function deleteDatabaseInstance($orgCode)
    {
        return $this->repository->deleteDatabaseInstance($orgCode);
    }
    public function getDatabaseInstance($orgCode)
    {
        return $this->repository->getDatabaseInstance($orgCode);
    }
}